//
//  FilesExampleViewController.m
//  FilesExample
//


#import "FilesExampleViewController.h"

@implementation FilesExampleViewController

- (void)writeStringToDirectory:(NSString *)dir {
    
    //create filename
    NSString *f = @"somefile.txt";
    NSString *path = [dir stringByAppendingPathComponent:f];
    
    //create string
    NSString *foo = @"some content";
    
    //save
    //写字符串到文件
    [foo writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    //read back in and log
    //从文件中读取字符串
    NSString *results = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"results: %@",results);
}

- (void)writeDictionaryToDirectory:(NSString *)dir
{
    //create file
    NSString *f = @"somefile.txt";
    NSString *path = [dir stringByAppendingPathComponent:f];
    
    //create dictionary
    NSString *string1 = @"some value";
    NSString *string2 = @"another value";
    NSNumber *num = [NSNumber numberWithInt:12345];
    NSArray *arr = [NSArray arrayWithObjects:
                    @"item1",
                    @"item2",
                    @"item3",nil];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          string1,@"item1", 
                          string2, @"item2", 
                          num, @"item3", 
                          arr, @"item4", nil];
    
    //save
    //写dict到文件
    [dict writeToFile:path atomically:YES];
    
    //read back and log
    //从文件中读去dict
    NSDictionary *results = [NSDictionary dictionaryWithContentsOfFile:path];
    NSLog(@"results: %@",results);
}

- (void)viewDidLoad {
    [self showFileManager];  
    
    //temp dir
    NSString *tempDir = NSTemporaryDirectory();
    NSLog(@"tempD: %@",tempDir);
    
    //documents dir
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    NSLog(@"documentsDir: %@",documentsDir);
    
    //resources file
    //NSBundle
    NSString *resourcesDir = [[NSBundle mainBundle] resourcePath];
    NSString *imageDir = [resourcesDir stringByAppendingPathComponent:@"apple.png"];
    NSLog(@"image path: %@",imageDir);
    
    //check if file exists in doc dir
    NSString *fileName = @"settings.plist";
    NSString *filePath = [documentsDir stringByAppendingPathComponent:fileName];
    //使用NSFileManager判断文件是否存在
    NSFileManager *fm = [NSFileManager defaultManager];
    BOOL exists = [fm fileExistsAtPath:filePath];	
    
    //copy from resources of bundle and save to documents dir
    if (! exists)
    {
        NSString *sourcePath =[resourcesDir stringByAppendingPathComponent:fileName];
        [fm copyItemAtPath:sourcePath toPath:filePath error:NULL];
    }
    
    exists = [fm fileExistsAtPath:filePath];	
    
    //write/read string
    [self writeStringToDirectory:documentsDir];
    
    //write/read dictionary
    [self writeDictionaryToDirectory:documentsDir];
}

#define LogDir(str, dir) NSLog(@"%@%@",str, [[NSFileManager defaultManager] directoryContentsAtPath:dir]);

- (void) showFileManager
{
	NSFileManager *fm = [NSFileManager defaultManager];
    
    //show home dictionary path
    NSString * homeDic = NSHomeDirectory();
    NSLog(@"homeDic: %@",homeDic);
    NSLog(@"%@",[fm directoryContentsAtPath:homeDic]);
    LogDir(homeDic, homeDic);
	
	// List the files in the Documents folder
	NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
	NSLog(@"%@",[fm directoryContentsAtPath:path]);
	
	// List the files in the application bundle
	path = [[NSBundle mainBundle] bundlePath];	
	NSLog(@"%@",[fm directoryContentsAtPath:path]);
	
	// Retrieve a path from the bundle
	NSBundle *mb = [NSBundle mainBundle];
	NSLog(@"%@", [mb pathForResource:@"Default" ofType:@"png"]);
	
	// Show move, copy, and remove
	NSError *error;
	
	// Create a file
	NSString *docspath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
	NSString *filepath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/testfile"];
	NSArray *array = [@"One Two Three" componentsSeparatedByString:@" "];
	[array writeToFile:filepath atomically:YES];
	NSLog(@"%@", [fm directoryContentsAtPath:docspath]);
	
	
	// Copy the file
	NSString *copypath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/copied"];
	if (![fm copyItemAtPath:filepath toPath:copypath error:&error])
	{
		NSLog(@"Copy Error: %@", [error localizedDescription]);
		return;
	}
	NSLog(@"%@", [fm directoryContentsAtPath:docspath]);
	
	// Move the file
	NSString *newpath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/renamed"];
	if (![fm moveItemAtPath:filepath toPath:newpath error:&error])
	{
		NSLog(@"Move Error: %@", [error localizedDescription]);
		return;
	}
	NSLog(@"%@", [fm directoryContentsAtPath:docspath]);
	
	// Remove a file
	if (![fm removeItemAtPath:copypath error:&error])
	{
		NSLog(@"Remove Error: %@", [error localizedDescription]);
		return;
	}
	NSLog(@"%@", [fm directoryContentsAtPath:docspath]);
	
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
}


- (void)dealloc {
    [super dealloc];
}

@end
